<template>
  <el-dialog
    v-model="visibility"
    :title="props.rowData.id ? config.button.text.edit : config.button.text.add"
    width="60%"
    append-to-body
    draggable
    :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="config.form.label.width"
      status-icon>
      <el-row>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="袋皮全称"
            prop="fullName">
            <el-input
              v-model="formData.fullName"
              placeholder="袋皮全称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="袋皮简称"
            prop="simpleName">
            <el-input
              v-model="formData.simpleName"
              placeholder="袋皮简称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="规格（KG）"
            prop="weightSpecification">
            <el-input-number
              :min="0.01"
              controls-position="right"
              :precision="2"
              style="width: 100%;"
              v-model="formData.weightSpecification"
              placeholder="规格"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="备注信息"
            prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="启用状态"
            prop="isEnable">
            <el-select
              v-model="formData.isEnable"
              placeholder="启用状态"
              clearable>
              <el-option
                :label="config.button.text.enable"
                :value="true" />
              <el-option
                :label="config.button.text.stop"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="袋皮图片"
            prop="fileDataJson">
            <UploadFile
              ref="uploadRef"
              :show="true"
              :file-uuids="fileDataList"
              @success="success"
              @delete-file="deleteFile" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
        <el-button
          type="primary"
          @click="saveEvent">
          {{ config.button.text.save }}
        </el-button>
      </div>
    </template>
    <el-dialog
      title="预览"
      v-model="dialogVisible">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image" />
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import ApiBag from "@/api/modules/base-bag"
import { useValidator } from "@/hooks/useValidator";
import ApiBaseRiceBarn from "@/api/modules/base-rice-barn";
import UploadFile from "@/components/UploadFile.vue"

const visibility = ref(false)
const formData = ref({})
const formRef = ref()

const fileDataList = ref();
const imageList = ref([]);
const dialogImageUrl = ref();
const dialogVisible = ref(false)

const { required, validate, clearValidate } = useValidator()

const formRules = {
  simpleName: [required("袋皮简称")],
  fullName: [required("袋皮全称")],
  weightSpecification: [required("规格")],
  isEnable: [required("启用状态", "change")],
  fileDataJson: [required("袋皮图片")],
}

// 上传文件成功回调
const success = (data) => {
  const file = formData.value.fileDataJson ? JSON.parse(formData.value.fileDataJson) : []
  file.push(data)
  formData.value.fileDataJson = JSON.stringify(file)
}

// 删除文件回调
const deleteFile = (data) => {
  const file = JSON.parse(formData.value.fileDataJson)
  formData.value.fileDataJson = JSON.stringify(file.filter(item => item === data))
}

const props = defineProps(["rowData"])

const emits = defineEmits(["save"])

watch(() => visibility.value, (newVal) => {
  if (newVal) {
    imageList.value = [];
    fileDataList.value = [];
    // 新增
    if (!props.rowData.id) {
      formData.value = {
        ...props.rowData,
        isEnable: true,
      };
    } else {
      formData.value = { ...props.rowData };
    }
    if (formData.value.fileDataJson && Array.isArray(JSON.parse(formData.value.fileDataJson))) {
      fileDataList.value = JSON.parse(formData.value.fileDataJson);
      if (fileDataList.value.length > 0) {
        getImageList();
      }
    } else {
      imageList.value = [];
    }
    setTimeout(() => {
      clearValidate(formRef.value);
    });
  }
}, { immediate: true });

//获取图片列表
const getImageList = async () => {
  let res = await ApiBaseRiceBarn.getPicture(fileDataList.value);
  imageList.value = res.data;
}

const saveEvent = async () => {
  await validate(formRef.value)
  formData.value.fileDataJson = JSON.stringify(fileDataList.value)
  if (formData.value.id) {
    await ApiBag.update(formData.value)
  } else {
    await ApiBag.insert(formData.value)
  }
  emits("save")
}

defineExpose({ visibility })
</script>

<style lang="scss" scoped>
.el-row {
  align-items: flex-start;
}

.imageList {
  color: #409eff;

  li {
    display: flex;
    align-items: center;

    .el-icon {
      margin-right: 5px;
    }
  }

  li:hover {
    cursor: pointer;
  }
}

@media screen and (max-width: 700px) {
  :deep(.el-form-item__label) {
    width: 80px !important;
  }
}
</style>
